import Vue from 'vue'
import VueRouter from 'vue-router'
import { isLogined } from '@/api/index'
Vue.use(VueRouter)

const routes = [
  {
    path: "/",
    redirect: "/home"
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/LoginView.vue")
  },
  {
    path: "/",
    name: "layout",
    meta: { title: "管理系统" },
    component: () => import("@/LayoutView.vue"),
    children: [
      {
        path: "home",
        name: "home",
        meta: { title: "主页" },
        component: () => import("@/views/HomeView.vue"),
      },
      {
        path: "user",
        name: "user",
        meta: { title: "用户管理" },
        component: () => import("@/views/UserView.vue"),
      },
      {
        path: "banner",
        name: "banner",
        meta: { title: "轮播图" },
        component: () => import("@/views/BannerView.vue"),
      },
      {
        path: "cateList",
        name: "cateList",
        component: () => import("@/views/CateList.vue"),
      },
      {
        path: "publish_article",
        name: "publish_article",
        meta: { title: "发布文章" },
        component: () => import("@/views/articles/PublishArticle.vue"),
      },
      {
        path: "article_list",
        name: "article_list",
        meta: { title: "文章列表" },
        component: () => import("@/views/articles/ArticleList.vue"),
      },
      {
        path: "setting",
        name: "setting",
        meta: { title: "系统界面设置" },
        component: () => import("@/views/SettingView.vue"),
      },
      {
        path: "MyRouter",
        name: "MyRouter",
        meta: { title: "导航设置" },
        component: () => import("@/views/RouterView.vue"),
      },
      {
        path: "note",
        name: "note",
        meta: { title: "随笔管理" },
        component: () => import("@/views/noteView.vue"),
      },
      {
        path: "photo",
        name: "photo",
        meta: { title: "相册管理" },
        component: () => import("@/views/photoView.vue"),
      },
      {
        path: "comment",
        name: "comment",
        component: () => import("@/views/CommentView.vue"),
      }
    ]
  }
]

const router = new VueRouter({
  routes
})


// // 全局前置守卫
router.beforeEach(async (to, from, next) => {
  const whiteList = ['/login']
  // console.log(to)
  // 如果访问的是路由，直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  let token = localStorage.getItem("AUTO_TOKEN")
  // 需要验证登录状态
  if (token) {
    try {
      const resData = await isLogined({ token })
      // console.log(resData)
      if (resData.code == 200 && resData.msg === '用户登录在线状态') {
        next()
      } else {
        // token失效，回到登录页
        localStorage.removeItem("AUTO_TOKEN")
        next('/login')
      }
    } catch (error) {
      localStorage.removeItem("AUTO_TOKEN")
      next('/login')
    }
  } else {
    // 没有token，回到登录页
    next('/login')
    return
  }
})

export default router
